package com.yds.dccjll.lib.base.webview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.yds.dccjll.lib.base.util.LogUtil;
import com.yds.dccjll.lib.base.util.SSLContextUtil;

import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertPathValidatorException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;

@SuppressLint({"NewApi", "HandlerLeak"})
class ReWebViewClient extends WebViewClient {
    private final String tag = ReWebViewClient.class.getSimpleName();

    private Context mContext;
    private WebView mWebView;
    private String mUrl;
    private SSLContext sslContext;
    private Boolean isHttps;

    private static final int TIME_OUT = 10000;

    ReWebViewClient(Context context, WebView webView, Boolean isHttps) {
        super();
        this.mContext = context;
        this.mWebView = webView;
        this.isHttps = isHttps;
        if (isHttps) {
//            sslContext = SSLContextUtil.getSSLContext(CacheData.getApp());
        }
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        if (isHttps) {
            return processRequest(request.getUrl());
        } else {
            return super.shouldInterceptRequest(view, request);
        }
    }

    private WebResourceResponse processRequest(Uri uri) {
        try {
            URL url = new URL(uri.toString());
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLContextUtil.HOSTNAME_VERIFIER);

            InputStream is = urlConnection.getInputStream();
            String contentType = urlConnection.getContentType();
            String encoding = urlConnection.getContentEncoding();

            if (contentType != null) {

                String mimeType = contentType;

                if (contentType.contains(";")) {
                    mimeType = contentType.split(";")[0].trim();
                }
                return new WebResourceResponse(mimeType, encoding, is);
            }

        } catch (SSLHandshakeException e) {
            if (isCause(CertPathValidatorException.class, e)) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new WebResourceResponse(null, null, null);
    }

    private boolean isCause(Class<? extends Throwable> expected, Throwable exc) {
        return expected.isInstance(exc) || (exc != null && isCause(expected, exc.getCause())
        );
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, Manifest.permission.CALL_PHONE)) {
//                Toast.makeText(mContext, R.string.permission_phone, Toast.LENGTH_LONG).show();
            } else {//请求授权
                ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.CALL_PHONE}, 0);
            }
            try {
                mContext.startActivity(intent);
            } catch (Exception e) {
                LogUtil.i(tag, e.getMessage());
            }
        } else if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
            view.loadUrl(url);
        } else {
            view.loadUrl(url);
        }
        LogUtil.i(tag, "shouldOverrideUrlLoading:" + url);
        return false;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        LogUtil.i(tag, "onPageStarted:" + new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date()) + url);

        //开始计时
        startTime();
        mUrl = url;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        LogUtil.i(tag, "onPageFinished:"+ new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date()) + url);

        if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        }

        //DialogUtil.dismissNetworkErrorDialog();
        //取消计时
        cancelTime();
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        LogUtil.i(tag, "onReceivedError:" + request.toString() + "error:" + error.getDescription().toString());
        LogUtil.i(tag, "The url = " + view.getUrl() + ", request = " + request.getUrl());

        // 取消计时
        cancelTime();

        // 避免因图片加载失败，而调整到重新加载页面
        String url = request.getUrl().toString();
        if (url.endsWith(".jpg") || url.endsWith(".JPG") || url.endsWith(".jpeg")
                || url.endsWith(".JPEG") || url.endsWith(".png") || url.endsWith(".PNG")) {
            return;
        }

        // 加载页面出错时
        showNetworkError();
    }

    @Override
    public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
        super.doUpdateVisitedHistory(view, url, isReload);
    }

    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request,
                                    WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
        LogUtil.i(tag, "onReceivedHttpError:" + request.toString()
            + "---onReceivedHttpError:" + errorResponse.toString());
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed();  // 证书错误时，接受所有网站的证书
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);

        LogUtil.i(tag, "onReceivedError:" + description + "error:" + errorCode);
        LogUtil.i(tag, "The url = " + view.getUrl() + ", The request = " + failingUrl);

        // 取消计时
        cancelTime();

        // 避免因图片加载失败，而调整到重新加载页面
        String url = failingUrl;
        if (url.endsWith(".jpg") || url.endsWith(".JPG") || url.endsWith(".jpeg")
            || url.endsWith(".JPEG") || url.endsWith(".png") || url.endsWith(".PNG")) {
            return;
        }

        // 加载页面出错时
        showNetworkError();
    }

    private Handler handler = new Handler();
    private Runnable timeoutRunnable = new Runnable() {
        @Override
        public void run() {
            if (mWebView.getProgress() < 100) {
                cancelTime();
                //DialogUtil.dismissProgressImageDialog();
                try {
                    showNetworkError();
                } catch (Exception e) {
                    e.printStackTrace();
//                    ToastUtil.showToast("无法显示错误页面");
                }
            }
        }
    };

    /**
     * 开始计时
     */
    private void startTime() {
        handler.removeCallbacks(timeoutRunnable);
        handler.postDelayed(timeoutRunnable, TIME_OUT);
    }

    /**
     * 取消计时
     */
    private void cancelTime() {
        handler.removeCallbacks(timeoutRunnable);
    }

    /**
     * 显示网络错误
     */
    private void showNetworkError() {
        mWebView.stopLoading();

        if (WebViewActivity.isAlive) {
//            DialogUtil.showNetWorkErrorDialog(mContext, new NetWorkErrorDialog.DialogListener() {
//                @Override
//                public void onRefresh() {
//                    mWebView.loadUrl(mUrl);
//            }
//
//                @Override
//                public void onBackHome() {
//                    ((Activity) mContext).finish();
//                }
//            });
        }
    }
}
